﻿package net.wangit.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;

import net.wangit.jdbc.table.TableConfigurationException;


@SuppressWarnings("unchecked")
public final class ClassUtil {

	public ClassUtil() {
	}

	public static URL getResource(String resourceName, Class callingClass) {
		URL url = null;
		url = Thread.currentThread().getContextClassLoader().getResource(
				resourceName);
		if (url == null)
			url = net.wangit.util.ClassUtil.class.getClassLoader().getResource(
					resourceName);
		if (url == null)
			url = callingClass.getClassLoader().getResource(resourceName);
		return url;
	}

	public static InputStream getResourceAsStream(String resourceName,
			Class callingClass) {
		try {
			URL url = getResource(resourceName, callingClass);
			return url == null ? null : url.openStream();
		} catch (IOException e) {
			return null;
		}
	}

	public static Object construct(String className, Object[] parameters)
			throws ClassNotFoundException {
		Constructor constructor;
		Class instance = Class.forName(className);
		Class types[] = new Class[parameters.length];
		for (int i = 0; i < types.length; i++)
			types[i] = Class.forName("java.lang.String");

		try {
			constructor = instance.getConstructor(types);
			return constructor.newInstance(parameters);
		} catch (Exception e) {
			throw new TableConfigurationException((new StringBuilder(
					"Could not construct Class: ")).append(className)
					.toString(), e);
		}
	}

	public static Class loadClass(String className)
			throws ClassNotFoundException {
		try {
			return Thread.currentThread().getContextClassLoader().loadClass(
					className);
		} catch (ClassNotFoundException e) {
			return Class.forName(className);
		}
	}

	public static boolean isPublic(Class clazz, Member member) {
		return Modifier.isPublic(member.getModifiers())
				&& Modifier.isPublic(clazz.getModifiers());
	}

	public static boolean isAbstractClass(Class clazz) {
		int modifier = clazz.getModifiers();
		return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
	}
}
